<?php

namespace app\weigeng\controller;

use support\Request;

class WebapiController
{

    public function index(Request $request)
    {
        return response(__CLASS__);
    }
    //远程开门
    public function opendoor(Request $request)
    {
        $url = 'http://47.103.32.234:61080/';
        // $url = 'http://192.168.1.196:61080/';
        $device_name = $request->post('device_name','');
        if(!$device_name){
            return json(['code'=>0,'msg'=>'缺失参数device_name']);
        }
        $door = $request->post('door',1);
        // $sncode = 133148600;
        $data['jsonrpc'] = '2.0';
        $data['method'] = '远程开门';
        $data['params'] = [['设备序列号'=>(int)$device_name,'门号'=>(int)$door]];
        $data['id'] = time();
        $res = $this->PostJson($url,$data);
        return json($res);
    }
    //发送json请求函数
    public function PostJson($url, $data = NULL,$headers="")
    {
        $curl = curl_init();
        $header =array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen(json_encode($data,320)),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        );
        if($headers){
            $header[]=$headers;
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            return 'data is null';
        }
        if (is_array($data)) {
            $data = json_encode($data,320);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 60); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return json_decode($res,true);
    }
}
